package org.rqb.panel;

import lombok.extern.slf4j.Slf4j;
import org.rqb.service.FileService;
import org.rqb.service.PointService;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.function.Consumer;

@Slf4j
public class ProxyPointPanel extends JPanel implements ActionListener {

    private JPanel panel;
    private CardLayout cardLayout;

    private final JTextField filePathField = new JTextField(30);
    private final JTextArea base64Area = new JTextArea(10, 40);
    private JButton browseButton;
    private JButton tronsBtn;
    private PointService pointService = new PointService();
    private FileService fileService = new FileService();
    private JButton copyButton;

    public ProxyPointPanel(JPanel panel, CardLayout cardLayout) {
        this.panel = panel;
        this.cardLayout = cardLayout;
        initUI();
        addDragDropSupport(); // 新增拖放支持
    }

    private void addDragDropSupport() {
        // 设置支持文件拖放的传输处理器
        base64Area.setTransferHandler(new TransferHandler() {
            @Override
            public boolean canImport(TransferSupport support) {
                // 只接受文件类型的拖放
                return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
            }

            @Override
            public boolean importData(TransferSupport support) {
                try {
                    // 获取拖放的文件列表
                    Transferable transferable = support.getTransferable();
                    java.util.List<File> files = (java.util.List<File>)
                            transferable.getTransferData(DataFlavor.javaFileListFlavor);

                    // 仅处理单个文件
                    if (files.size() != 1) {
                        JOptionPane.showMessageDialog(
                                ProxyPointPanel.this,
                                "请拖放单个文件！",
                                "错误",
                                JOptionPane.ERROR_MESSAGE
                        );
                        return false;
                    }

                    // 更新文件路径文本框
                    File file = files.get(0);
                    filePathField.setText(file.getAbsolutePath());
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            fileService.readFileToText(file.getAbsolutePath(), base64Area);

                        }
                    });
                    return true;
                } catch (Exception e) {
                    log.error("文件拖放失败", e);
                    JOptionPane.showMessageDialog(
                            ProxyPointPanel.this,
                            "文件读取失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                    return false;
                }
            }
        });

    }


    private void initUI() {
        setLayout(new BorderLayout(5, 5));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 文件选择面板
        JPanel filePanel = new JPanel(new BorderLayout(5, 5));
        browseButton = new JButton("选择文件");
        browseButton.addActionListener(this);

        tronsBtn = new JButton("转换");
        tronsBtn.addActionListener(this);

        // 创建按钮容器面板（使用FlowLayout让按钮水平排列）
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        buttonPanel.add(browseButton);
        buttonPanel.add(tronsBtn);

        filePanel.add(new JLabel("选择文件:"), BorderLayout.WEST);
        filePanel.add(filePathField, BorderLayout.CENTER);
        filePanel.add(buttonPanel, BorderLayout.EAST); // 将按钮面板放在右侧

        // Base64展示区域
        base64Area.setEditable(false);
        base64Area.setLineWrap(true);
        base64Area.setWrapStyleWord(true);
        // 修改滚动面板部分
        JScrollPane scrollPane = new JScrollPane(base64Area);
        scrollPane.setBorder(BorderFactory.createTitledBorder("文件内容"));

        // 创建带有复制按钮的面板
        JPanel bottomPanel = new JPanel(new BorderLayout());
        copyButton = new JButton("复制到剪贴板");
        copyButton.addActionListener(this);

        // 将按钮放在右下角
        JPanel buttonContainer = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonContainer.add(copyButton);
        bottomPanel.add(scrollPane, BorderLayout.CENTER);
        bottomPanel.add(buttonContainer, BorderLayout.SOUTH);

        add(filePanel, BorderLayout.NORTH);
        add(bottomPanel, BorderLayout.CENTER); // 替换原来的 scrollPane
    }







    // 可选：添加获取数据的方法
    public String getBase64Content() {
        return base64Area.getText();
    }

    public String getSelectedFilePath() {
        return filePathField.getText();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JButton) {
            if (e.getSource() == browseButton) {
                handleFileSelection(e);
            } else if (e.getSource() == tronsBtn) {
                trans(getSelectedFilePath());
            } else if (e.getSource() == copyButton) {
                handleCopy(e);
            }

        }

    }

    private void handleCopy(ActionEvent e) {
        String content = base64Area.getText();
        if (content.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    "内容为空，无需复制",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        try {
            StringSelection selection = new StringSelection(content);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(selection, null);
            JOptionPane.showMessageDialog(this,
                    "已复制到剪贴板",
                    "成功",
                    JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            log.error("复制失败", ex);
            JOptionPane.showMessageDialog(this,
                    "复制失败: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private void trans(String filePath) {
        if (filePath == null || filePath.isEmpty()) { //选中的为空
            JOptionPane.showMessageDialog(this,"请选择文件！！！","error",JOptionPane.ERROR_MESSAGE);
            return;
        }
        pointService.ymlTransToV2rayNBase64(filePath, s -> base64Area.setText(s));


    }

    private void handleFileSelection(ActionEvent event) {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) { //获取到文件路径
            File selectedFile = fileChooser.getSelectedFile();
            filePathField.setText(selectedFile.getAbsolutePath());

        }
    }




}